const fs = require('fs')
const mongoose = require('mongoose')
const bannerModel = require('../../dao/schema/bannerSchema')
const demoModel = require('../../dao/schema/demoSchema')
require('dotenv').config() //加载环境变量
// 连接到数据库
mongoose
  .connect(`mongodb://${process.env.DB_HOST}:27017/${process.env.DB_NAME}`)
  .then(() => {
    console.log('数据库链接成功')
    //查找有用的图片路径
    findUsefulPic().then((res) => {
      if (res.code !== '0') {
        console.log('查询失败1:' + res)
        return
      } else if (res.code == '0') {
        console.log(res.data, 'usefulImgsList')
        clearUploads(res.data)
      } else {
        console.log('查询失败2:')
      }
    })
  })
  .catch((err) => {
    console.log(err, '数据库链接失败')
  })

async function findUsefulPic() {
  let usefulImgs = []
  let p1 = await bannerModel.find({}, 'midImg bigImg')
  p1.forEach((item) => {
    let midName = item.midImg
      .split('/')
      .pop()
      .replace(/\.\w+$/, '')
    let bigName = item.bigImg
      .split('/')
      .pop()
      .replace(/\.\w+$/, '')
    usefulImgs.push(midName)
    usefulImgs.push(bigName)
  })
  let p2 = await demoModel.find({}, 'thumb ')
  p2.forEach((item) => {
    let name = item.thumb
      .split('/')
      .pop()
      .replace(/\.\w+$/, '')
    usefulImgs.push(name)
  })
  // 关闭连接
  mongoose.disconnect()
  return {
    code: '0',
    data: usefulImgs,
  }
}

function clearUploads(list) {
  console.log('开始删除')
  //删除img文件夹下的图片
  fs.readdir(__dirname + '/uploads', function (err, files) {
    if (err) {
      return console.log('读取文件夹失败！' + err.message)
    }
    if (files.length === 0) {
      console.log('文件夹为空！')
      return
    }
    files.forEach(function (item) {
      //正则去除文件后缀名
      let reg = /\.\w+$/
      if (list.includes(item.replace(reg, ''))) {
        console.log('包含' + item)
        return
      }
      console.log('删除不包含' + item)
      fs.unlink(__dirname + '/uploads/' + item, function (err) {
        if (err) {
          return console.log('删除文件失败！' + item + '失败原因:' + err)
        }
        console.log(`删除文件${item}成功！`)
      })
    })
  })
}
